package com.xfgg.cloud.app;

import com.xfgg.cloud.adapter.request.LoginRequest;
import com.xfgg.cloud.domain.model.aggregate.User;
import com.xfgg.cloud.domain.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 权限服务
 *
 * @author xfgg
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class AuthService {
    private final UserService userService;
    private final StringRedisTemplate stringRedisTemplate;

    public String createToken(LoginRequest loginRequest) {
        User user = userService.getUserByName(loginRequest.getUserName(), loginRequest.getPassWord());
        if (!user.getJwtUser().isEnabled()) {
            throw new RuntimeException("");
        }
        String token = user.getToken();
        stringRedisTemplate.opsForValue().set(user.getUserInfo().getUserName(), token);
        log.info(loginRequest.getUserName() + "登录");
        return token;
    }

    public void removeToken() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Optional.ofNullable(authentication).orElseThrow(() -> new RuntimeException(""));
        Optional.ofNullable(authentication.getPrincipal()).orElseThrow(() -> new RuntimeException(""));
        String userName = authentication.getPrincipal().toString();
        stringRedisTemplate.delete(userName);
        log.info(userName + "退出登录");
    }
}
